package com.gensdai.leliang.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.gensdai.leliang.R;
import com.gensdai.leliang.activity.SearchActivity;
import com.gensdai.leliang.activity.UserCenter;
import com.gensdai.leliang.activity.UserNews;
import com.gensdai.leliang.activity.user_enter;
import com.gensdai.leliang.base.BaseFragment;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 首页分类fragment
 * Created by liutao on 2017/5/23.
 */

public class FragmentTypeCard extends BaseFragment {

    public static final String EXTRA_TYPE_POSITION = "ext:position";
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    @BindView(R.id.typeViewpager)
    ViewPager typeViewpager;

    @BindView(R.id.geshu)
    TextView geshu;

    private int extra_id = -1;

    Unbinder unbinder;


    private List<Fragment> list_fragment;
    private List<String> list_title;
    private List<Integer> list_id;
    Find_tab_Adapter fAdapter;

    public static FragmentTypeCard NewInstance() {

        return new FragmentTypeCard();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            extra_id = getArguments().getInt(EXTRA_TYPE_POSITION, -1);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_type, container, false);
        unbinder = ButterKnife.bind(this, v);
        return v;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initTablayout();
//        if (extra_id != -1) {
//            updateview(extra_id);
//        }
    }

    @Override
    public void onStart() {
        super.onStart();
        Query();
    }


    SharedPreferences share;

    @OnClick(R.id.messagebox)
    public void onMessageClick(View v) {
        share = getActivity().getSharedPreferences("User", getActivity().MODE_PRIVATE);
        if (share.getBoolean("enter_state", false)) {
            Intent go_usercenter = new Intent(getActivity(), UserNews.class);
            startActivity(go_usercenter);
        } else {
            startActivity(new Intent(getActivity(), user_enter.class));
        }
    }

    @OnClick(R.id.search)
    public void onSearchClick(View v) {
        startActivity(new Intent(getActivity(), SearchActivity.class));
    }

    private void initTablayout() {
        tablayout.setTabGravity(TabLayout.GRAVITY_FILL);
        tablayout.setTabMode(TabLayout.MODE_FIXED);


        list_fragment = new ArrayList<>();
        ContentTypeFragment contentTypeFragment = ContentTypeFragment.NewInstance(extra_id);
        BrandFragment brand = new BrandFragment();
        list_fragment.add(contentTypeFragment);
        list_fragment.add(brand);
        list_title = new ArrayList<>();
        list_title.add("分类");
        list_title.add("品牌");

        list_id = new ArrayList<>();
        list_id.add(0);
        list_id.add(1);

        tablayout.addTab(tablayout.newTab().setText(list_title.get(0)));
        tablayout.addTab(tablayout.newTab().setText(list_title.get(1)));


        fAdapter = new Find_tab_Adapter(getActivity().getSupportFragmentManager(), list_fragment, list_title, list_id);
        //viewpager加载adapter
        typeViewpager.setAdapter(fAdapter);

        tablayout.setupWithViewPager(typeViewpager);

        typeViewpager.setCurrentItem(0);

    }

    public void updateview(int id) {

        Log.e("updateview_id", id + "");

        if (typeViewpager != null && fAdapter != null) {
            typeViewpager.setCurrentItem(0);
            ContentTypeFragment fragment = (ContentTypeFragment) fAdapter.getItem(0);
            if (fragment != null) {
                fragment.updateRadioPosition(id);
            }
        }
    }


    public class Find_tab_Adapter extends FragmentPagerAdapter {

        private List<Fragment> list_fragment;                         //fragment列表
        private List<String> list_Title;                              //tab名的列表
        private List<Integer> ids;                              //tab的id


        public Find_tab_Adapter(FragmentManager fm, List<Fragment> list_fragment, List<String> list_Title, List<Integer> ids) {
            super(fm);
            this.list_fragment = list_fragment;
            this.list_Title = list_Title;
            this.ids = ids;

        }

        @Override
        public Fragment getItem(int position) {
            return list_fragment.get(position);
        }

        @Override
        public int getCount() {
            return list_Title.size();
        }

        //此方法用来显示tab上的名字
        @Override
        public CharSequence getPageTitle(int position) {

            return list_Title.get(position % list_Title.size());
        }

        @Override
        public long getItemId(int position) {
            return ids.get(position);
        }
    }

    /**
     * 查询消息
     */
    private void Query() {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("userNo", getActivity().getSharedPreferences("User", getActivity().MODE_PRIVATE).getString("userno", ""));
        toStrNews(loginParams);
    }

    //返回字符串类型
    private void toStrNews(Map<String, String> loginParams) {
        ApiService.getInstance(getActivity()).CQUERY_MESSAGE_COUNT_Receipt(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(FragmentEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        try {
                            int i = 0;
                            if (new json_base().GOOD(s)) {
                                String[] list = (String[]) new json_base().JsonCall(new JSONObject(s));
                                i = Integer.parseInt(list[0]) + Integer.parseInt(list[1]);
                                if (i > 0) {
                                    if (i > 99) {
                                        geshu.setText("99+");
                                    } else {
                                        geshu.setText(i + "");
                                    }
                                    geshu.setVisibility(View.VISIBLE);
                                } else {
                                    geshu.setVisibility(View.INVISIBLE);
                                }
                            } else {
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
